#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include "Comm.hpp"

using namespace std;

void handler(int signo)
{
    std::cout << "signo: " << signo << std::endl;
    exit(0);
}

#define Retry_count 5

void Usage(const std::string& process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

bool visitserver(std::string& serverip, uint16_t& serverport, int *cnt)
{
    string inbuffer;
    char serverlist[1024];//提供的服务列表
    ssize_t n, m;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cerr << "socket error" << endl;
        return false;
    }
    bool ret = true;

    //bind
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);//主机序->网络序
    n = connect(sockfd, CONV(&server), sizeof(server));//connect后服务器就会Push：这将调用DefaultService，打印出服务列表
    if (n < 0)
    {
        cerr << "connect error" << endl;
        ret = false;
        goto END;
    }
    *cnt = 0;

    m = read(sockfd, serverlist, sizeof(serverlist)-1);//在此接受服务列表
    if (m > 0)
    {
        serverlist[m] = 0;
        cout << "服务器提供的服务列表是: " << serverlist << endl;
    }

    // 并没有向server一样，产生新的sockfd.未来我们就用connect成功的sockfd进行通信即可.
    cout << "请你选择服务#  ";
    getline(cin, inbuffer);//选择想要的服务
    if (inbuffer == "quit")
        return true;

    // std::cout << "echo : " << inbuffer << std::endl;
    n = write(sockfd, inbuffer.c_str(), inbuffer.size());//发送服务
    if(n > 0)
    {
        char buffer[1024];
        m = read(sockfd, buffer, sizeof(buffer)-1);//读取收到的回复
        if(m > 0)
        {
            buffer[m] = 0;
            cout << buffer << endl;
        }else if (m == 0){
            return true;
        }else{
            ret = false;
            goto END;
        }
    }else
    {
        std::cout << "hello write error" << std::endl;
        ret = false;
        goto END;
    }
    END:
        close(sockfd);
        return ret;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[1]);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    int cnt = 1;
    while(cnt <= Retry_count)
    {
        bool result = visitserver(serverip, serverport, &cnt);
        if (result)
        {
            break;
        }
        else
        {
            sleep(1);
            std::cout << "server offline, retrying..., count : " << cnt << std::endl;
            cnt++;
        }
    }
     if (cnt >= Retry_count)
    {
    std:
        cout << "server offline" << std::endl;
    }
    return 0;
}